package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.*;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.SettingVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class SettingManager {

    @DubboReference
    private QuestionService questionService;

    @DubboReference
    private NotificationService notificationService;

    // 查询通用设置
    public ResponseEntity findSettingVo() {
        // 1.获取线程内user对象
        Long userId = UserHolder.get().getId();
        // 2.查询陌生人问题
        Question question = questionService.findByUserId(userId);
        // 3.查询推送通知
        Notification notification = notificationService.findByUserId(userId);
        // 4.封装settingVo
        SettingVo vo = new SettingVo();
        vo.setId(userId); // 用户id
        if (question != null) {
            vo.setStrangerQuestion(question.getStrangerQuestion()); // 陌生人问题
        }
        vo.setPhone(UserHolder.get().getMobile());// 用户手机号
        if (notification != null) { // 推送通知
            vo.setLikeNotification(notification.getLikeNotification());
            vo.setPinglunNotification(notification.getPinglunNotification());
            vo.setGonggaoNotification(notification.getGonggaoNotification());
        }
        // 5.返回vo
        return ResponseEntity.ok(vo);
    }

    // 设置陌生人问题
    public void setQuestion(String content) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.查询此用户是否设置过陌生人问题
        Question question = questionService.findByUserId(userId);
        // 3.判断
        if (question == null) {// 新增
            question = new Question();
            question.setUserId(userId);
            question.setStrangerQuestion(content);
            questionService.save(question);
        } else { // 修改
            question.setStrangerQuestion(content);
            questionService.update(question);
        }
    }

    // 设置推送通知
    public void setNotification(Notification param) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.rpc查询
        Notification notification = notificationService.findByUserId(userId);
        // 3.判断
        if (notification == null) { // 新增
            param.setUserId(userId); // 补齐用户id
            notificationService.save(param);
        } else { // 更新
            notification.setLikeNotification(param.getLikeNotification()); // 补齐喜欢
            notification.setPinglunNotification(param.getPinglunNotification()); // 补齐评论
            notification.setGonggaoNotification(param.getGonggaoNotification()); // 补齐公告
            notificationService.update(notification);
        }
    }

    @DubboReference
    private BlackListService blackListService;

    @DubboReference
    private UserInfoService userInfoService;

    // 黑名单查询
    public ResponseEntity findBalckListByPageBeanVo(Integer pageNum, Integer pageSize) {
        // 1.获取线程内的userId
        Long userId = UserHolder.get().getId();
        // 2.根据三个条件查询
        PageBeanVo pageBeanVo = blackListService.findByPage(userId, pageNum, pageSize);
        // 3.根据黑名单用户id查询userInfo
        // 3-1 获取黑名单list
        List<BlackList> blackListList = (List<BlackList>) pageBeanVo.getItems();
        // 3-2 声明userInfoList
        List<UserInfo> userInfoList = new ArrayList<>();
        // 3-3 完成封装设置
        if (CollectionUtil.isNotEmpty(blackListList)) {
            for (BlackList blackList : blackListList) {
                // 获取黑名单用户id
                Long blackUserId = blackList.getBlackUserId();
                // 查询userInfo
                UserInfo userInfo = userInfoService.findById(blackUserId);
                // 设置到list集合
                userInfoList.add(userInfo);
            }
        }
        // 4.替换 将userInfoList设置到pageBeanVo
        pageBeanVo.setItems(userInfoList);
        // 5.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 移除黑名单
    public void deleteBalckList(Long blackUserId) {
        // 1.获取线程内userId
        Long userId = UserHolder.get().getId();
        // 2.rpc删除
        blackListService.delete(userId, blackUserId);
    }

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //发送短信验证码
    public void sendSms() {
        //1.获取线程内的 userId
        Long userId = UserHolder.get().getId();

        //通过 ID 查询数据库获得手机号
        User user = phoneService.findUser(userId);

        String phone = user.getMobile();

        // 2.生成6位随机数
        String code = RandomUtil.randomNumbers(6);
        code = "123456";
        // 3.调用阿里云发送短信
        // smsTemplate.sendSms(phone, code);  // TODO 产品上线后实现短信发送
        // 4.将验证码存入redis
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, code, Duration.ofMinutes(5));
    }

    @DubboReference
    private PhoneService phoneService;

    //验证码校验
    public ResponseEntity checkVerificationCode(String verificationCode) {
        //返回结果
        Map<String, Object> map = new HashMap<>();
        //获得当前用户ID
        Long userId = UserHolder.get().getId();
        //通过 ID 查询数据库获得手机号
        User user = phoneService.findUser(userId);
        //1.获取 redis 中的验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + user.getMobile());
        //2.对比验证码是否一致
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        //清除短信验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + user.getMobile());

        map.put("verification",true);
        return ResponseEntity.ok(map);
    }

    //保存新的手机号
    public void uptadePhoneNum(String phone) {
        //1.获取线程内的 userId
        Long userId = UserHolder.get().getId();
        User user = phoneService.findUser(userId);
        //2.完善 user 对象
        user.setMobile(phone);
        //3.调用 rpc 修改
        phoneService.updatePhone(user);
    }
}
